/**
 * 
 */
package co.com.ebusiness.trader.pages;

import java.text.NumberFormat;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;
import org.got5.tapestry5.jquery.ImportJQueryUI;

import co.com.ebusiness.trader.core.model.Empresa;
import co.com.ebusiness.trader.model.Inventario;
import co.com.ebusiness.trader.seguridad.model.Usuario;
import co.com.ebusiness.trader.seguridad.model.UsuarioEmpresa;
import co.com.ebusiness.trader.services.TraderService;

/**
 * @author Luis Agudelo
 *
 */
@Import(stylesheet = { "context:css/jquery/jquerydatatables.css" })
//Apply the "smoothness" theme (downloaded from http://jqueryui.com/themeroller/)
@ImportJQueryUI(theme = "context:css/jquery/themes/smoothness/jquery-ui-1.8.23.custom.css")
public class ActualizarInventario {

	
		// Screen fields
		@Property
		private Inventario inventario;
		
		// Other pages
		@InjectPage
		private co.com.ebusiness.trader.pages.Cuenta indexPage;
		
		@Property
		@SuppressWarnings("unused")
		private co.com.ebusiness.trader.model.DetalleInventario detalle;
		
		@Property
		@SuppressWarnings("unused")
		private NumberFormat numberFormat;

		// Generally useful bits and pieces

		@Component(id = "inventarioForm")
		private BeanEditForm inventarioForm;

		@Inject
		private TraderService traderService;
		
		@Inject
	 	private Request request;
		
		
		
		// setupRender() is called by Tapestry right before it starts rendering the page.

		void setupRender() {
			numberFormat = NumberFormat.getInstance();
		}
		
		// onPassivate() is called by Tapestry to get the activation context to put in the URL.
		Inventario onPassivate() {
			return inventario;
		}
		
		// onActivate() is called by Tapestry to pass in the activation context from the URL.
		void onActivate(Inventario inventario) {
			this.inventario = inventario;
		}
		
		public void set(Inventario inventario) {
			this.inventario = inventario;
		}

		// PersonForm bubbles up the PREPARE_FOR_SUBMIT event during form submission.
		void onPrepareForSubmit() {
			// Get objects for the form fields to overlay.
			inventario = traderService.getInventario(inventario.getIdInv());
			
			if (inventario == null) {
				inventario = new Inventario();
				inventarioForm.recordError("El inventario ha sido borrado.");
			}
		}

		// PersonForm bubbles up the VALIDATE event when it is submitted
		@CommitAfter
		void onValidateFromInventarioForm() {

			if (inventarioForm.getHasErrors()) {
				// We get here only if a server-side validator detected an error.
				return;
			}

			try {
				Session session = request.getSession(false);
				Empresa empresa = null;
				Usuario usuario = null;
				if (session != null && session.getAttribute("state:Index::empresa") != null){
					empresa = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getEmpresa();
					usuario = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getUsuario();
		 		}
				inventario.setEmpresa(empresa);
				inventario.setUsuario(usuario);
				
				traderService.guardarInventario(inventario);
			}
			catch (Exception e) {
				// Display the cause. In a real system we would try harder to get a user-friendly message.
				inventarioForm.recordError(e.getMessage());
			}
		}

		// PersonForm bubbles up SUCCESS or FAILURE when it is submitted, depending on whether VALIDATE records an error

		Object onSuccess() {
			return indexPage;
		}
		
		public JSONObject getOptions() {
			
			// The available options are documented at http://www.datatables.net/ref
			
			JSONObject options = new JSONObject();
			options.put("bJQueryUI", "true");
			return options;
		}

		// Handle event "delete"
		@CommitAfter
		void onDelete(co.com.ebusiness.trader.model.DetalleInventario detalle) {
			
			try {
				
				inventario.setCantidad(inventario.getCantidad()-detalle.getCantidad());
				inventario.setValorCosto(inventario.getValorCosto()-(detalle.getPrecio().getCosto()*detalle.getCantidad()));
				inventario.setValorVentaMayor(inventario.getValorVentaMayor()-(detalle.getPrecio().getVentamayor()*detalle.getCantidad()));
				inventario.setValorVentaMenor(inventario.getValorVentaMenor()-(detalle.getPrecio().getVentamenor()*detalle.getCantidad()));
				
				inventario.getDetalles().remove(detalle);
				
				traderService.guardarInventario(inventario);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		
}
